package com.example.demo.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

@Configuration
@PropertySource("classpath:application-thisdatasource.properties")
@MapperScan(basePackages = ThisMyBatisConfig.PACKAGES, sqlSessionFactoryRef = "thisSqlSessionFactory")
public class ThisMyBatisConfig {

    static final String PACKAGES = "com.example.demo.DBServer.thisDatabase.dao";

    @ConfigurationProperties(prefix = "spring.this.datasource")
    @Primary
    @Bean(name = "thisDataSource")
    public DataSource druid(){
        return new DruidDataSource();
    }

    @Bean(name = "thisTransactionManager")
    @Primary
    public DataSourceTransactionManager masterTransactionManager(@Qualifier("thisDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "thisConfiguration")
    @ConfigurationProperties(prefix = "mybatis.this.configuration")
    public org.apache.ibatis.session.Configuration globalConfiguration() {
        return new org.apache.ibatis.session.Configuration();
    }

    @Bean(name = "thisSqlSessionFactory")
    @Primary
    public SqlSessionFactory masterSqlSessionFactory(@Qualifier("thisDataSource") DataSource dataSource,
                                                     @Qualifier("thisConfiguration") org.apache.ibatis.session.Configuration config) throws Exception {
//        config.addInterceptor(new SqlInterceptor());
        final SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
        sessionFactoryBean.setDataSource(dataSource);
        sessionFactoryBean.setConfiguration(config);
        return sessionFactoryBean.getObject();
    }

}
